package com.asset.dispoal.file.agreementCaseData.service.commom;

import com.asset.dispoal.business.bsAgreement.dto.EvidenceDataRequest;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.MatchSuccessEvidence;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.RemoveEvidenceContract;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.mapper.BusinessDataManageMapper;
import com.asset.dispoal.business.bsEvidenceRecognition.dto.ContractEvidenceResponse;
import com.asset.dispoal.file.agreementCaseData.domain.dto.EvidenceDataExport;
import com.asset.dispoal.file.agreementCaseData.dto.ExportEvidenceDataRequest;
import com.asset.dispoal.file.common.ExcelExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommandNoResult;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.spring.util.DataUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Component
public class ExportEvidenceDataCommand implements BaseCommandNoResult<Map<String, Object>> {

    @Autowired
    private BusinessDataManageMapper businessDataManageMapper;

    @Override
    public void execute(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        ExportEvidenceDataRequest request = (ExportEvidenceDataRequest) map.get("request");
        // 查询搜索的对应数据
        List<Map<String, String>> mapList = businessDataManageMapper.queryDataDetail(request.getAssetInstBatchId());
        List<Map<String, Object>> agreementDataList = businessDataManageMapper.queryResultByEvidenceDataRequest(DataUtil.copyTo(request, EvidenceDataRequest.class), mapList);
        //匹配成功的证据
        List<MatchSuccessEvidence> matchSuccessEvidenceList = businessDataManageMapper.queryMatchSuccessEvidence(request.getAssetInstBatchId(), request.getEvidenceTypeId(), null);
        //删除的证据
        List<RemoveEvidenceContract> removeEvidenceContractList = businessDataManageMapper.queryRemoveEvidenceContract(request.getAssetInstBatchId(), request.getEvidenceTypeId(), null);
        //数据需要匹配上的种类
        List<ContractEvidenceResponse> evidenceResponseList = businessDataManageMapper.queryEvidenceTypeByAssetInstBatchId(request.getAssetInstBatchId(), request.getEvidenceTypeId(), null);
        //根据证据种类进行分组
        Map<String, List<MatchSuccessEvidence>> evidenceTypeSuccessMap = matchSuccessEvidenceList.stream().collect(Collectors.groupingBy(MatchSuccessEvidence::getEvidenceTypeId));
        Map<String, List<RemoveEvidenceContract>> removeEvidenceContractMap = removeEvidenceContractList.stream().collect(Collectors.groupingBy(RemoveEvidenceContract::getEvidenceTypeId));

        List<EvidenceDataExport> exportList = new CopyOnWriteArrayList<>();

        agreementDataList.parallelStream().forEach(agreementData -> {
            AtomicBoolean checkAgreementEvidence = new AtomicBoolean(Boolean.TRUE);
            for (ContractEvidenceResponse evidence : evidenceResponseList) {
                //当前种类下的证据
                List<MatchSuccessEvidence> evidenceTypeList = evidenceTypeSuccessMap.get(evidence.getId());
                //删除种类下的证据
                List<RemoveEvidenceContract> removeEvidenceTypeList = removeEvidenceContractMap.get(evidence.getId());
                List<MatchSuccessEvidence> matchSuccessEvidences = evidenceTypeList;
                if (CollectionUtil.isNotEmpty(removeEvidenceTypeList)) {
                    Set<String> removeEvidenceIdSet = removeEvidenceTypeList.stream()
                            .filter(removeEvidenceType -> agreementData.get("contractId").equals(removeEvidenceType.getContractId()))
                            .map(RemoveEvidenceContract::getEvidenceId)
                            .collect(Collectors.toSet());
                    matchSuccessEvidences = matchSuccessEvidences.stream().filter(evidenceType -> !removeEvidenceIdSet.contains(evidenceType.getEvidenceId())).collect(Collectors.toList());
                }
                if (CollectionUtil.isEmpty(matchSuccessEvidences)) {
                    checkAgreementEvidence.compareAndSet(Boolean.TRUE, Boolean.FALSE);
                    break;
                }
                AtomicBoolean checkEvidenceType = new AtomicBoolean(Boolean.FALSE);

                for (MatchSuccessEvidence matchSuccessEvidence : matchSuccessEvidences) {
                    //无需匹配的证据直接返回当前成功
                    if (StringUtil.isEmpty(matchSuccessEvidence.getAlias())) {
                        checkEvidenceType.compareAndSet(Boolean.FALSE, Boolean.TRUE);
                        break;
                    }
                    //证据匹配上的返回成功
                    try {
                        if (agreementData.get(matchSuccessEvidence.getAlias()).equals(matchSuccessEvidence.getResult())) {
                            checkEvidenceType.compareAndSet(Boolean.FALSE, Boolean.TRUE);
                            break;
                        }
                    } catch (Exception ignore) {
                    }


                }
                if (!checkEvidenceType.get()) {
                    checkAgreementEvidence.compareAndSet(Boolean.TRUE, Boolean.FALSE);
                    break;
                }
            }
            if (!checkAgreementEvidence.get()) {
                EvidenceDataExport dataExport = new EvidenceDataExport();
                dataExport.setNo((String) agreementData.get("no"));
                dataExport.setName((String) agreementData.get("borrowerName"));
                dataExport.setIdcard((String) agreementData.get("borrowerIdcard"));
                dataExport.setLenders((String) agreementData.get("lenders"));
                exportList.add(dataExport);
            }
        });

        ExcelExport.export(response, "证据查阅导出", exportList, EvidenceDataExport.class);
    }
}